import Promise from 'promise';
import * as ResultMsg from '../constrants/ResultMsg';
import config from '../config';
import * as cache from '../common/cache';
import { errorJson, successJson } from '../common/response';
import { checkId, checkDoc } from '../common/check';
import { MessageProxy } from '../proxy';

export {
  unreadCount,
  userMessages,
  read,
};

async function unreadCount(req, res, next) {
  const appId = res.locals.appId;
  const userId = req.session.user._id;

  try {
    const count = await MessageProxy.count(appId, userId, false);
    successJson(req, res, { count });
  } catch (err) {
    next(err);
  }
}

async function userMessages(req, res, next) {
  const appId = res.locals.appId;
  const userId = req.session.user._id;
  const currentPage = parseInt(req.body.currentPage, 10) || 1;
  const type = req.body.type || 'unRead';

  const limit = config.list_topic_count;
  const options = { skip: (currentPage - 1) * limit, limit, sort: '-top -last_reply_at' };

  const hasRead = type !== 'unRead';

  try {
    const messages = await MessageProxy.findByUserId(appId, userId, hasRead, options);
    const count = await MessageProxy.count(appId, userId, type);
    const pages = Math.ceil(count / limit);
    successJson(req, res, { data: messages, pages, currentPage });
  } catch (err) {
    next(err);
  }
}

async function read(req, res, next) {
  const appId = res.locals.appId;
  const messageId = req.body.messageId;

  const data = {
    has_read: true,
  };

  try {
    await checkId(messageId);
    await MessageProxy.update(appId, messageId, data);
    successJson(req, res, { msg: '已标记为已读' });
  } catch (err) {
    next(err);
  }
}
